<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('标注历史管理')" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight">
        <div class="row">
            <div class="col-sm-12">
                <div class="ibox">
                    <div class="ibox-title">
                        <h5>标注历史管理</h5>
                        <div class="ibox-tools">
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <div class="row">
                            <div class="col-sm-12">
                                <form id="form-search" class="form-horizontal">
                                    <div class="row">
                                        <div class="col-sm-2">
                                            <div class="form-group">
                                                <label class="col-sm-5 control-label">左脚诊断：</label>
                                                <div class="col-sm-7">
                                                    <select name="leftFoot" class="form-control">
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-sm-2">
                                            <div class="form-group">
                                                <label class="col-sm-5 control-label">右脚诊断：</label>
                                                <div class="col-sm-7">
                                                    <select name="rightFoot" class="form-control">
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-sm-2">
                                            <div class="form-group">
                                                <label class="col-sm-5 control-label">腿型分类：</label>
                                                <div class="col-sm-7">
                                                    <select name="leg" class="form-control">
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-sm-2">
                                            <div class="form-group">
                                                <label class="col-sm-5 control-label">标注用户：</label>
                                                <div class="col-sm-7">
                                                    <select name="updateUserId" class="form-control">
                                                        <option value="">全部</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-sm-2">
                                            <div class="form-group">
                                                <label class="col-sm-5 control-label">评论状态：</label>
                                                <div class="col-sm-7">
                                                    <select name="remark" class="form-control">
                                                        <option value="">全部</option>
                                                        <option value="0">未评论</option>
                                                        <option value="1">已评论</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-sm-2">
                                            <div class="form-group">
                                                <div class="col-sm-12">
                                                    <button type="button" class="btn btn-sm btn-primary" onclick="$.table.search()">
                                                        <i class="fa fa-search"></i> 搜索
                                                    </button>
                                                    <button type="reset" class="btn btn-sm btn-default" onclick="$.form.reset()">
                                                        <i class="fa fa-refresh"></i> 重置
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-sm-12 select-table table-striped">
                                <table id="bootstrap-table" data-mobile-responsive="true"></table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 大图预览弹窗 -->
    <div class="modal fade" id="imagePreviewModal" tabindex="-1" role="dialog" aria-labelledby="imagePreviewModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" style="width: 85%; max-width: 1000px; margin: 5% auto;">
            <div class="modal-content" style="max-height: 85vh;">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="imagePreviewModalLabel">图片预览</h4>
                </div>
                <div class="modal-body text-center" style="padding: 20px; background-color: #f5f5f5; overflow: hidden; height: calc(85vh - 120px);">
                    <div style="position: relative; height: calc(85vh - 160px); display: flex; align-items: center; justify-content: center; overflow: hidden;">
                        <img id="previewImage" src="" alt="预览图片" style="max-width: 100%; max-height: 70%; cursor: grab; transition: transform 0.3s ease; position: relative; z-index: 1;">
                    </div>
                    <div style="margin-top: 15px; position: relative; z-index: 2;">
                        <button type="button" class="btn btn-default" onclick="zoomPreviewImage(1.2)">
                            <i class="fa fa-search-plus"></i> 放大
                        </button>
                        <button type="button" class="btn btn-default" onclick="zoomPreviewImage(0.8)">
                            <i class="fa fa-search-minus"></i> 缩小
                        </button>
                        <button type="button" class="btn btn-default" onclick="resetPreviewZoom()">
                            <i class="fa fa-refresh"></i> 重置
                        </button>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
    
    <th:block th:include="include :: footer" />
    <script th:inline="javascript">
        var prefix = ctx + "system/picture";
        var currentPreviewZoom = 1;
        var isDragging = false;
        var dragStartX = 0;
        var dragStartY = 0;
        var imageStartX = 0;
        var imageStartY = 0;
        
        // 全局变量存储字典数据
        var dictData = {
            foot_type: [],
            leg_type: []
        };
        
        // 标注员用户列表
        var tagMakerUsers = [];

        // 加载字典数据
        function loadDictData() {
            // 加载右腿诊断字典
            $.ajax({
                url: ctx + "system/dict/data/type/foot_type",
                type: "GET",
                async: false,
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        dictData.foot_type = result.data;
                        // 填充下拉框
                        var options = '';
                        $.each(result.data, function(index, item) {
                            if (item.dictValue == 0) {
                                    options += '<option value="' + item.dictValue + '" selected>' + item.dictLabel + '</option>';
                            } else {
                                    options += '<option value="' + item.dictValue + '">' + item.dictLabel + '</option>';
                            }
                        });
 
                        $('select[name="rightFoot"]').html(options);
                        $('select[name="leftFoot"]').html(options);
                    }
                }
            });
            
            // 加载腿型分类字典
            $.ajax({
                url: ctx + "system/dict/data/type/leg_type",
                type: "GET",
                async: false,
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        dictData.leg_type = result.data;
                        // 填充下拉框
                        var options = '';
                        $.each(result.data, function(index, item) {
                            if (item.dictValue == 0) {
                                    options += '<option value="' + item.dictValue + '" selected>' + item.dictLabel + '</option>';
                            } else {
                                    options += '<option value="' + item.dictValue + '">' + item.dictLabel + '</option>';
                            }
                        });
                        $('select[name="leg"]').html(options);
                    }
                }
            });
            
            // 加载标注员用户列表
            $.ajax({
                url: ctx + "system/user/listByRoleKey/tagMaker",
                type: "GET",
                async: false,
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        tagMakerUsers = result.data;
                        // 填充标注用户下拉框
                        var options = '<option value="">全部</option>';
                        $.each(result.data, function(index, item) {
                            options += '<option value="' + item.userId + '">' + item.userName + '</option>';
                        });
                        $('select[name="updateUserId"]').html(options);
                    }
                }
            });
        }

        // 获取字典标签
        function getDictLabel(dictType, dictValue) {
            var dictArray = dictData[dictType] || [];
            for (var i = 0; i < dictArray.length; i++) {
                if (dictArray[i].dictValue == dictValue) {
                    return dictArray[i].dictLabel;
                }
            }
            return dictValue || '-';
        }

        // 查询参数处理
        function queryParams(params) {
            var search = $.table.queryParams(params);
            // 确保包含所有筛选参数
            search.updateUserId = $('select[name="updateUserId"]').val();
            search.rightFoot = $('select[name="rightFoot"]').val();
            search.leftFoot = $('select[name="leftFoot"]').val();
            search.leg = $('select[name="leg"]').val();
            search.remark = $('select[name="remark"]').val();
            search.beginTime = $('#beginTime').val();
            search.endTime = $('#endTime').val();
            // 保存筛选条件到localStorage，供详情页面使用
            saveFilterParamsToLocalStorage();
            return search;
        }
        
        // 保存筛选条件到localStorage
        function saveFilterParamsToLocalStorage() {
            try {
                const filterParams = {
                    updateUserId: $('select[name="updateUserId"]').val(),
                    rightFoot: $('select[name="rightFoot"]').val(),
                    leftFoot: $('select[name="leftFoot"]').val(),
                    leg: $('select[name="leg"]').val(),
                    remark: $('select[name="remark"]').val(),
                    beginTime: $('#beginTime').val(),
                    endTime: $('#endTime').val()
                };
                localStorage.setItem('pictureListFilterParams', JSON.stringify(filterParams));
                console.log('筛选条件已保存到localStorage:', filterParams);
            } catch (e) {
                console.error('保存筛选条件失败:', e);
            }
        }
        
        // 为筛选条件控件添加change事件监听
        function bindFilterChangeEvents() {
            // 为所有筛选控件添加change事件
            $('select[name="updateUserId"], select[name="rightFoot"], select[name="leftFoot"], select[name="leg"], select[name="remark"]').on('change', function() {
                saveFilterParamsToLocalStorage();
                // 刷新表格数据
                $.table.refresh();
            });
            
            // 为日期控件添加change事件
            $('#beginTime, #endTime').on('change', function() {
                saveFilterParamsToLocalStorage();
                // 刷新表格数据
                $.table.refresh();
            });
        }

        $(function() {
            // 先加载字典数据
            loadDictData();
            
            // 绑定筛选条件变更事件
            bindFilterChangeEvents();
            
            // 初始化时保存一次筛选条件
            saveFilterParamsToLocalStorage();
            
            var options = {
                url: prefix + "/allAnnotationHistory",
                modalName: "标注历史",
                search: false,
                showToggle: false,
                showColumns: false,
                showRefresh: true,
                pageSize: 10,
                pageList: [10, 25, 50],
                queryParams: queryParams,
                columns: [{
                    checkbox: true
                },
                {
                    field: 'id',
                    title: '图片ID',
                    align: 'center',
                    valign: 'middle'
                },
                {
                    field: 'url',
                    title: '缩略图',
                    align: 'center',
                    valign: 'middle',
                    formatter: function(value, row, index) {
                        if (value) {
                            return '<img src="' + value + '" class="img-thumbnail" style="width: 60px; height: 40px; object-fit: cover; cursor: pointer; border: 1px solid #ddd;" onclick="showImagePreview(\'' + value + '\', \'' + row.id + '\')" title="点击查看大图">';
                        }
                        return '-';
                    }
                },
                {
                    field: 'leftFoot',
                    title: '左脚诊断',
                    align: 'center',
                    valign: 'middle',
                    formatter: function(value, row, index) {
                        return getDictLabel('foot_type', value);
                    }
                },
                {
                    field: 'rightFoot',
                    title: '右脚诊断',
                    align: 'center',
                    valign: 'middle',
                    formatter: function(value, row, index) {
                        return getDictLabel('foot_type', value);
                    }
                },
                {
                    field: 'leg',
                    title: '腿型分类',
                    align: 'center',
                    valign: 'middle',
                    formatter: function(value, row, index) {
                        return getDictLabel('leg_type', value);
                    }
                },
                {
                    field: 'updateUserId',
                    title: '标注用户',
                    align: 'center',
                    valign: 'middle',
                    formatter: function(value, row, index) {
                        // 从标注员用户列表中查找用户名
                        if (value && tagMakerUsers) {
                            for (var i = 0; i < tagMakerUsers.length; i++) {
                                if (tagMakerUsers[i].userId == value) {
                                    return tagMakerUsers[i].userName;
                                }
                            }
                        }
                        return value || '-';
                    }
                },
                {
                    field: 'updateTime',
                    title: '标注时间',
                    align: 'center',
                    valign: 'middle',
                    formatter: function(value, row, index) {
                        return $.common.dateFormat(value, 'yyyy-MM-dd HH:mm:ss');
                    }
                },
                {
                    field: 'remark',
                    title: '评论状态',
                    align: 'center',
                    valign: 'middle',
                    formatter: function(value, row, index) {
                        return value == 1 ? '<span class="label label-primary">已评论</span>' : '<span class="label label-default">未评论</span>';
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    valign: 'middle',
                    formatter: function(value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-info btn-xs" href="javascript:void(0)" onclick="viewDetail(' + row.id + ')" title="查看详情"><i class="fa fa-eye"></i>详情</a>');
                        return actions.join('');
                    }
                }]
            };
            $.table.init(options);
            
            // 绑定大图预览弹窗事件
            $("#imagePreviewModal").on("hidden.bs.modal", function() {
                resetPreviewZoom();
            });
        });
        
        /**
         * 显示大图预览
         */
        function showImagePreview(imageSrc, imageName) {
            if (imageSrc) {
                $("#previewImage").attr("src", imageSrc);
                $("#imagePreviewModalLabel").text("图片预览 - " + imageName);
                $("#imagePreviewModal").modal('show');
                resetPreviewZoom();
                
                // 绑定滚轮缩放事件
                setTimeout(function() {
                    bindPreviewWheelEvent();
                }, 300);
                
                // 确保弹窗居中显示
                setTimeout(function() {
                    $("#imagePreviewModal").modal('handleUpdate');
                }, 150);
            }
        }
        
        /**
         * 绑定预览图片滚轮事件
         */
        function bindPreviewWheelEvent() {
            $("#previewImage").off("wheel.preview").on("wheel.preview", function(e) {
                e.preventDefault();
                var delta = e.originalEvent.deltaY;
                if (delta > 0) {
                    zoomPreviewImage(0.9);
                } else {
                    zoomPreviewImage(1.1);
                }
            });
        }
        
        /**
         * 预览图片缩放
         */
        function zoomPreviewImage(factor) {
            currentPreviewZoom *= factor;
            currentPreviewZoom = Math.max(0.1, Math.min(currentPreviewZoom, 3));
            $("#previewImage").css("transform", "scale(" + currentPreviewZoom + ")");
            
            if (currentPreviewZoom > 1.5) {
                $("#previewImage").css("margin-bottom", "80px");
                enablePreviewDrag();
            } else {
                $("#previewImage").css("margin-bottom", "0");
                disablePreviewDrag();
            }
        }
        
        /**
         * 重置预览缩放
         */
        function resetPreviewZoom() {
            currentPreviewZoom = 1;
            $("#previewImage").css("transform", "scale(1)");
            $("#previewImage").css("margin-bottom", "0");
            $("#previewImage").css({"left": "0", "top": "0"});
            disablePreviewDrag();
            
            setTimeout(function() {
                bindPreviewWheelEvent();
            }, 100);
        }
        
        /**
         * 启用预览图片拖动
         */
        function enablePreviewDrag() {
            var $img = $("#previewImage");
            $img.css("cursor", "grab");
            
            $img.off("mousedown.preview").on("mousedown.preview", function(e) {
                isDragging = true;
                dragStartX = e.clientX;
                dragStartY = e.clientY;
                var currentPos = $img.position();
                imageStartX = currentPos.left;
                imageStartY = currentPos.top;
                $img.css("cursor", "grabbing");
                e.preventDefault();
            });
            
            $(document).off("mousemove.preview").on("mousemove.preview", function(e) {
                if (isDragging) {
                    var deltaX = e.clientX - dragStartX;
                    var deltaY = e.clientY - dragStartY;
                    var newX = imageStartX + deltaX;
                    var newY = imageStartY + deltaY;
                    $img.css({"left": newX + "px", "top": newY + "px"});
                }
            });
            
            $(document).off("mouseup.preview").on("mouseup.preview", function() {
                if (isDragging) {
                    isDragging = false;
                    $img.css("cursor", "grab");
                }
            });
        }
        
        /**
         * 禁用预览图片拖动
         */
        function disablePreviewDrag() {
            $("#previewImage").css("cursor", "grab");
            $("#previewImage").off("mousedown.preview");
            $(document).off("mousemove.preview mouseup.preview");
            isDragging = false;
        }
        
        /**
         * 查看详情
         */
        function viewDetail(pictureId) {
            // 获取当前页面的筛选条件
            const filterParams = {
                updateUserId: $('select[name="updateUserId"]').val(),
                rightFoot: $('select[name="rightFoot"]').val(),
                leftFoot: $('select[name="leftFoot"]').val(),
                leg: $('select[name="leg"]').val(),
                beginTime: $('#beginTime').val(),
                endTime: $('#endTime').val()
            };
            
            // 构建带筛选条件的URL
            let url = prefix + "/historyDetail/" + pictureId;
            let hasParams = false;
            
            // 添加筛选参数到URL
            for (const [key, value] of Object.entries(filterParams)) {
                if (value !== undefined && value !== null && value !== '') {
                    url += (hasParams ? '&' : '?') + key + '=' + encodeURIComponent(value);
                    hasParams = true;
                }
            }
            
            console.log('打开详情页面，带筛选条件:', url);
            
            // 使用$.modal.open方法打开弹窗，通过iframe加载historyDetail.html
            // 设置更大的初始尺寸，避免从小到大的变动效果
            // $.modal.open("标注历史详情", url, "1600px", "900px");
            var index = layer.open({
                type: 2,
                title: '标注详情',
                shadeClose: true,
                shade: 0.8,
                area: ['95%', '95%'],
                content: url,
                success: function(layero, index) {
                    // 弹窗加载成功后的回调 - 移除全屏逻辑，保持原有尺寸
                    // layer.full(index); // 注释掉这行，避免自动全屏
                }
            });
        }
        
        // 重新标注功能已移除，可通过查看详情中的保存修改按钮进行标注更新
    </script>
</body>
</html>